//
//  SPStoreViewController.m
//  Sport
//
//  Created by 周志贤 on 2018/4/6.
//  Copyright © 2018年 Cass. All rights reserved.
//

#import "SPStoreViewController.h"
#import "SPInfoModel.h"

#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "SPAMapNaviController.h"
#import "SPParkingController.h"

@interface SPStoreViewController ()<AMapSearchDelegate,MAMapViewDelegate,AMapLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet UIView *mapViewBackground;
@property (strong, nonatomic) MAMapView *mapView;
@property (strong, nonatomic) AMapSearchAPI *search;

@property (strong, nonatomic) AMapGeoPoint *endPoint;
@property (strong, nonatomic) AMapGeoPoint *startPoint;
@property (nonatomic,strong)NSArray *pathPolylines;
@property (nonatomic,assign)NSInteger *totalTime;//导航总时间

@property (weak, nonatomic) IBOutlet UILabel *venueName;
@property (weak, nonatomic) IBOutlet UIImageView *venueImg;
@property (weak, nonatomic) IBOutlet UILabel *venueAd;
@property (weak, nonatomic) IBOutlet UILabel *grade;
@property (weak, nonatomic) IBOutlet UILabel *price;
@property (weak, nonatomic) IBOutlet UIButton *collect;
@property (strong, nonatomic) NSNumber *collectID;
@property (strong, nonatomic) NSMutableArray *collectArray;
@property (strong, nonatomic) NSUserDefaults *userDefaults;
@property (nonatomic, strong) UIButton *toParkButton;
@end

@implementation SPStoreViewController


- (UIButton *)toParkButton{
    if (!_toParkButton) {
        _toParkButton = [[UIButton alloc]init];
        [_toParkButton setBackgroundColor:[UIColor grayColor]];
        [_toParkButton setTitle:@"停车场" forState:UIControlStateNormal];
        [_toParkButton addTarget:self action:@selector(toPark:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _toParkButton;
}
- (void)configToParkButton{
    [self.view addSubview:self.toParkButton];
    [self.toParkButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.mapViewBackground).offset(-20);
        make.bottom.equalTo(self.mapViewBackground).offset(-10);
        make.width.equalTo(@80);
        make.height.equalTo(@40);
    }];
}
- (void)toPark:(UIButton *)button{
    SPParkingController *parkingVC = [[UIStoryboard storyboardWithName:@"Venue" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:NSStringFromClass([SPParkingController class])];
    [self.navigationController pushViewController:parkingVC animated:YES];
}
#pragma mark ---高德
-(MAMapView *)mapView{
    if (_mapView == nil) {
        CGFloat W = self.mapViewBackground.frame.size.width;
        CGFloat H = self.mapViewBackground.frame.size.height;
        _mapView = [[MAMapView alloc]initWithFrame:CGRectMake(0, 0, W, H)];
        _mapView.delegate = self;
        [self.mapViewBackground addSubview:_mapView];
        _mapView.showsUserLocation = YES;
        [_mapView setZoomLevel:15 animated:YES];
        _mapView.userTrackingMode = MAUserTrackingModeFollow;
     
    }
    return _mapView;
}

-(AMapSearchAPI *)search{
    if (_search == nil) {
        _search = [[AMapSearchAPI alloc]init];
        self.search.delegate = self;
    }
    return _search;
}



-(void)findLocation{
    [self search];
    AMapGeocodeSearchRequest *request = [[AMapGeocodeSearchRequest alloc]init];
    request.city =[self.userDefaults objectForKey:@"locationCity"];
    request.address =self.infoModel.venuesadd;
    [self.search AMapGeocodeSearch:request];

}

-(CLLocationDistance)CalculationDistance:(CLLocationCoordinate2D)location1  WithLocation2:(CLLocationCoordinate2D)location2{
    MAMapPoint point1 = MAMapPointForCoordinate(location1);
    MAMapPoint point2 = MAMapPointForCoordinate(location2);
    CLLocationDistance distance = MAMetersBetweenMapPoints(point1, point2);
    return distance;
}

-(void)showRout{
    AMapDrivingRouteSearchRequest *navi = [[AMapDrivingRouteSearchRequest alloc] init];
    navi.requireExtension = YES;
    navi.strategy = 1;
    navi.origin = _startPoint;
    navi.destination = _endPoint;
    [self.search AMapDrivingRouteSearch:navi];
}

- (void)onGeocodeSearchDone:(AMapGeocodeSearchRequest *)request response:(AMapGeocodeSearchResponse *)response{
    NSLog(@"回调方法 地理编码");
    if (response.count ==0) {
        return;
    }
    NSArray *data = response.geocodes;
    for (AMapGeocode *dict in data) {
        _endPoint = dict.location;
    }
    MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc]init];
    CLLocationCoordinate2D locate = CLLocationCoordinate2DMake(_endPoint.latitude, _endPoint.longitude);
    _mapView.centerCoordinate = locate;
    pointAnnotation.coordinate = locate;
    pointAnnotation.title = self.infoModel.venuesname;
    CLLocationDistance distance =  [self CalculationDistance:locate WithLocation2:self.mapView.userLocation.coordinate];
    pointAnnotation.subtitle = [NSString stringWithFormat:@"距离:%0.1fKM",distance/1000];
    NSLog(@"%f",self.mapView.userLocation.coordinate.longitude);
     _startPoint =  [AMapGeoPoint locationWithLatitude:self.mapView.userLocation.coordinate.latitude
                             longitude:self.mapView.userLocation.coordinate.longitude];
      [_mapView addAnnotation:pointAnnotation];
    [self showRout];
    
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAPinAnnotationView*annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.canShowCallout= YES;       //设置气泡可以弹出，默认为NO
        annotationView.animatesDrop = YES;        //设置标注动画显示，默认为NO
        annotationView.draggable = YES;        //设置标注可以拖动，默认为NO
        annotationView.pinColor = MAPinAnnotationColorPurple;
        return annotationView;
    }
    return nil;
}

-(void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response{
    NSLog(@"运行路径规划回调方法");
    //先删除之前的路线
    [_mapView removeOverlays:_pathPolylines];
    
    if(response.route == nil){
        NSLog(@"路线获取失败");
        return ;
    }
    //解析response获取路径信息
    NSLog(@"漂亮!");
 
    
    NSMutableArray *arr1 = [[NSMutableArray alloc]init];
    for (AMapStep *step in response.route.paths[0].steps) {
        
        //路段坐标点串解析
        NSArray *array = [step.polyline componentsSeparatedByString:@";"];
        CLLocationCoordinate2D commonPolylineCoords[array.count];
        NSInteger i = 0;
        for (NSString *str1 in array) {
            NSArray *arr1 = [str1 componentsSeparatedByString:@","];
            commonPolylineCoords[i].longitude = [arr1[0] floatValue];
            commonPolylineCoords[i].latitude  = [arr1[1] floatValue];
            i++;
        }
        MAPolyline *commPolyline = [MAPolyline polylineWithCoordinates:commonPolylineCoords count:array.count];
        [arr1 addObject:commPolyline];
    }

    _pathPolylines = arr1;
    [_mapView addOverlays:_pathPolylines];    
    
}

//画线回调函数
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay
{
    NSLog(@"运行画线回调方法");
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:overlay];
        
        polylineRenderer.lineWidth    = 4.f;
        polylineRenderer.strokeColor  = [UIColor blueColor];
        polylineRenderer.lineJoinType = kMALineJoinRound;
        polylineRenderer.lineCapType  = kMALineCapRound;
        
        return polylineRenderer;
    }
    return nil;
}

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"规划失败");
    NSLog(@"Error: %@", error);
}

#pragma mark ---分割线 ------

- (void)viewWillAppear:(BOOL)animated{
    _userDefaults = [NSUserDefaults standardUserDefaults];
    if (![_userDefaults objectForKey:@"collect"]) {
        [_userDefaults setObject:self.collectArray forKey:@"collect"];
    }
    _collectID = self.infoModel.ID;
    if ([[_userDefaults objectForKey:@"collect"] containsObject:_collectID]) {
        [_collect setTitle:@"取消收藏" forState:(UIControlStateNormal)];
    }
    else{
        [_collect setTitle:@"收藏" forState:(UIControlStateNormal)];
    }
    
}



- (IBAction)amapNavi:(id)sender {
    SPAMapNaviController *navi = [[UIStoryboard storyboardWithName:@"Venue" bundle:[NSBundle mainBundle]]instantiateViewControllerWithIdentifier:@"SPAMapNaviController"];
    navi.point =(AMapNaviPoint*)_endPoint;
    [self.navigationController pushViewController:navi animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    [self mapView];
    [self findLocation];
    [self configToParkButton];
}

- (NSMutableArray *)collectArray{
    if (_collectArray == nil) {
        _collectArray = [NSMutableArray array];
    }
    return _collectArray;
}


- (void)loadData{
    _venueName.text = self.infoModel.venuesname;
    [_venueImg sd_setImageWithURL:[NSURL URLWithString:self.infoModel.venuesimage] placeholderImage:[UIImage imageNamed:@"ha"]];
    _venueAd.text = self.infoModel.venuesadd;
    _grade.text = [NSString stringWithFormat:@"评分%@",self.infoModel.venuesmark];
    _price.text = [NSString stringWithFormat:@"价格%@元",self.infoModel.venuesprice];
}
- (IBAction)collectClick:(id)sender {
    NSArray *tArray = [_userDefaults objectForKey:@"collect"];
    if (_collectArray.count != tArray.count) {//防止多次点击“收藏”按钮时，_collectArray多次添加重复元素
        //    self.collectArray = [_userDefaults objectForKey:@"collect"]
        for (NSNumber *t in tArray) {
            [self.collectArray addObject:t];//从_userDefaults中依次取出元素放入collectArray
        }
    }
    _collectID = self.infoModel.ID;
    if (![self.collectArray containsObject:_collectID]) {
        [_collectArray addObject:_collectID];
        [_userDefaults setObject:self.collectArray forKey:@"collect"];
        [SPHUDUtil showHUDWithDismissTimeInterval:1 message:@"收藏成功" hudType:SPHUDTypeSuccess];
        [_collect setTitle:@"取消收藏" forState:(UIControlStateNormal)];
    }
    else{
        [_collectArray removeObject:_collectID];
        [_userDefaults setObject:self.collectArray forKey:@"collect"];
        [SPHUDUtil showHUDWithDismissTimeInterval:1 message:@"取消成功" hudType:SPHUDTypeSuccess];
        [_collect setTitle:@"收藏" forState:(UIControlStateNormal)];
    }
    NSLog(@"%@",self.collectArray);
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
